//
//  MeDetailViewController.m
//  wifi4.2
//
//  Created by 郭四虎 on 15/11/11.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "MeDetailViewController.h"
#import "ChangePasswordController.h"
#import "ForgetPasswordControllerViewController.h"
#import "BindNumViewController.h"

@interface MeDetailViewController ()<UIActionSheetDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UIView *_backView;
}
@property (weak, nonatomic) IBOutlet UIImageView *iconIma;
@property (weak, nonatomic) IBOutlet UIButton *nameBtn;
@property (weak, nonatomic) IBOutlet UITextField *nameTf;
@property (weak, nonatomic) IBOutlet UILabel *numLb;

@property (weak, nonatomic) IBOutlet UILabel *sexWoman;
@property (weak, nonatomic) IBOutlet UILabel *sexMan;

@property (weak, nonatomic) IBOutlet UIButton *dateBtn;
@property (weak, nonatomic) IBOutlet UISwitch *sexSwitch;
@property (strong, nonatomic) IBOutlet UIDatePicker *datePiker;

@property (strong, nonatomic) UIActionSheet *myActionSheet;

@end

@implementation MeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"个人资料";
    [self initUI];
    self.navigationController.navigationBar.tintColor = [UIColor redColor];
}

- (void)initUI
{
        
    Myuser *user = [Myuser sharedUser];
    
    if ( [self valiMobile:user.login_id]) {
        
        self.numLb.text = user.login_id;
        
    }else{
        self.numLb.text = @"";
    }
    
    
    self.nameTf.hidden = YES;
    [self.nameBtn setTitle:user.name forState:UIControlStateNormal];
    
    
    
    _iconIma.layer.cornerRadius = 30*SCALEY;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(upPhoto)];
    
    [_iconIma addGestureRecognizer:tap];
    
    if (user.icon) {
        [self.iconIma sd_setImageWithURL:[NSURL URLWithString:user.icon]placeholderImage:[UIImage imageNamed:@"icon3.png"]];
    }else{
        self.iconIma.image = [UIImage imageNamed:@"add"];
    }
    
    if ([user.sex integerValue]) {
        _sexSwitch.on = NO;
        
    }else{
        _sexSwitch.on = YES;
    }
    if (_sexSwitch.on) {
        _sexWoman.textColor = [UIColor whiteColor];
    }else{
        _sexWoman.textColor = [UIColor redColor];
    }
    
    if (user.birthday) {
        
        NSDateFormatter *formater = [[NSDateFormatter alloc]init];
        [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss.s"];
        NSDate *dat = [formater dateFromString:user.birthday];
        [formater setDateFormat:@"yyyy-MM-dd"];
        NSString *datestr = [formater stringFromDate:dat];
        
        [_dateBtn setTitle:datestr forState:UIControlStateNormal];
    }else{
        [_dateBtn setTitle:@"" forState:UIControlStateNormal];
    }
    
 //   [self getOtherInfo];
}

- (void)upPhoto
{
//    if ( ![self valiMobile:_numLb.text]) {
//        
//        [self.view Message:@"尚未绑定手机号" HiddenAfterDelay:1];
//        return;
//    }
    self.myActionSheet = [[UIActionSheet alloc]
                          initWithTitle:nil
                          delegate:self
                          cancelButtonTitle:@"取消"
                          destructiveButtonTitle:nil
                          otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
    
    [self.myActionSheet showInView:self.view];
}

- (void)getOtherInfo
{
    NSDictionary *parameter;
    if ([self valiMobile:USERID]) {
        parameter = @{@"login_id":USERID};

    }else{
        parameter = @{@"uuid":USERID};
    }
    
    [MyAFN POST:USERINFO parameters:parameter block:^(id responseObject) {
        NSDictionary *response = responseObject;
        if ([[response objectForKey:@"status"]integerValue]) {
            
            if ( [self valiMobile:[response objectForKey:@"login_id"]]) {
                
                self.numLb.text = USERID;
                
            }else{
                self.numLb.text = @"";
            }
            
            if ([response objectForKey:@"sex"]) {
                if ([[response objectForKey:@"sex"]integerValue]) {
                    _sexSwitch.on = NO;
                    [self modifySex:_sexSwitch];
                }else{
                    _sexSwitch.on = YES;
                    [self modifySex:_sexSwitch];
                }
            }
            
            if ([response objectForKey:@"birthday"]) {
                
                NSDateFormatter *formater = [[NSDateFormatter alloc]init];
                [formater setDateFormat:@"yyyy-MM-dd HH:mm:ss.s"];
                NSDate *dat = [formater dateFromString:[response objectForKey:@"birthday"]];
                [formater setDateFormat:@"yyyy-MM-dd"];
                NSString *datestr = [formater stringFromDate:dat];
                
                [_dateBtn setTitle:datestr forState:UIControlStateNormal];
            }
            
            
        }
        
    } error:^(NSError *error) {
        
    } fromController:self];
}

- (IBAction)modifyName:(id)sender {
    
//    if ( ![self valiMobile:_numLb.text]) {
//        
//        [self.view Message:@"尚未绑定手机号" HiddenAfterDelay:1];
//        return;
//    }
    
    self.nameTf.hidden = NO;
    if (_nameBtn.currentTitle) {
        self.nameTf.text = _nameBtn.currentTitle;
    }
    [self.nameTf becomeFirstResponder];
    
    _nameBtn.hidden = YES;
}
- (IBAction)modifyBirthday:(id)sender {

//    if ( ![self valiMobile:_numLb.text]) {
//        
//        [self.view Message:@"尚未绑定手机号" HiddenAfterDelay:1];
//        return;
//    }
    
    if (!_datePiker) {
        _datePiker = [[UIDatePicker alloc]initWithFrame:CGRectMake(10, 200, WIDTH-20, 200)];
        _datePiker.datePickerMode = UIDatePickerModeDate;
        _datePiker.backgroundColor = [UIColor whiteColor];
        _datePiker.maximumDate = [NSDate date];
    }
    
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:SCREEN];
        [self setAnchorPoint:CGPointMake(0.8, 0.8) forView:_backView];
        _backView.transform = CGAffineTransformMakeScale(0.0001, 0.00001);
        
        
        
        [_backView addSubview:_datePiker];
        
        _datePiker.superview.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
    }
    
    
//    _datePiker.frame = CGRectMake(10, 200, WIDTH-20, 200);
        
//    _backView.frame = SCREEN;
   
    [UIView animateWithDuration:0.5 animations:^{
        
        _backView.transform = CGAffineTransformMakeScale(1.0, 1.0);
        
    }];
    [self.view addSubview:_backView];
}

- (void)setAnchorPoint:(CGPoint)point forView:(UIView *)view
{
    CGPoint oldP = view.frame.origin;
    view.layer.anchorPoint = point;
    CGPoint newP = view.frame.origin;
    
    CGPoint translation;
    translation.x = newP.x - oldP.x;
    translation.y = newP.y - oldP.y;
    
    view.center = CGPointMake(view.center.x - translation.x, view.center.y - translation.y);
}

- (IBAction)modifyNum:(id)sender {
    
//        ForgetPasswordControllerViewController *fc = [[ForgetPasswordControllerViewController alloc]init];
//        
//        fc.isBinding = YES;
//        fc.uuid = USERID;
//        fc.bound = ^(NSString *num){
//            
//            _numLb.text = num;
//        };
    BindNumViewController *bind = [[BindNumViewController alloc]init];
    bind.uuid = USERID;
    bind.bound = ^(NSString *num){
        
        _numLb.text = num;
    };
    [self.navigationController pushViewController:bind animated:YES];
    
}
- (IBAction)modifyPassword:(id)sender {
    
    if ( ![self valiMobile:_numLb.text]) {
        
        [self.view Message:@"尚未绑定手机号" HiddenAfterDelay:1];
        return;
    }
    
    ForgetPasswordControllerViewController *fc = [[ForgetPasswordControllerViewController alloc]init];
    [self.navigationController pushViewController:fc animated:YES];
}

- (IBAction)modifySex:(UISwitch *)sender {
    
//    if ( ![self valiMobile:_numLb.text]) {
//        
//        [self.view Message:@"尚未绑定手机号" HiddenAfterDelay:1];
//        sender.on = YES;
//        return;
//    }
    NSNumber *sex;
    if (sender.on) {
        _sexWoman.textColor = [UIColor whiteColor];
        sex = @(!sender.on);
    }else{
        _sexWoman.textColor = [UIColor redColor];
        sex = @(!sender.on);
    }
    NSDictionary *dic = @{@"login_id":USERID,@"sex":sex};
    [self modifyUserInfo:dic back:^(bool issuccess) {
       
        if (issuccess) {
            [Myuser sharedUser].sex = [@(!sender.on) stringValue];
        }
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (_nameTf.text.length) {
        if (![_nameBtn.currentTitle isEqualToString:_nameTf.text]) {
            
            
            NSDictionary *dic = @{@"login_id":[Myuser sharedUser].login_id,@"name":_nameTf.text};
            [self modifyUserInfo:dic back:^(bool isSuccess) {
               
                if (isSuccess) {
                    [_nameBtn setTitle:_nameTf.text forState:UIControlStateNormal];
                    
                    [Myuser sharedUser].name = _nameTf.text;
                    [[NSUserDefaults standardUserDefaults]setObject:_nameTf.text forKey:@"username"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
                }
            }];
        }
        
    }
    _nameTf.hidden = YES;
    _nameBtn.hidden = NO;
    
    
    UITouch *tou = [touches anyObject];
    if (tou.view == _sexSwitch||tou.view == _sexMan||tou.view == _sexWoman) {
//        if ( ![self valiMobile:_numLb.text]) {
//            
//            [self.view Message:@"尚未绑定手机号" HiddenAfterDelay:1];
//            //sender.on = YES;
//            return;
//        }
        NSNumber *sex;
        if (!_sexSwitch.on) {
            _sexWoman.textColor = [UIColor whiteColor];
            sex = @(!_sexSwitch.on);
        }else{
            _sexWoman.textColor = [UIColor redColor];
            sex = @(!_sexSwitch.on);
        }
        NSDictionary *dic = @{@"login_id":[Myuser sharedUser].login_id,@"sex":sex};
        [self modifyUserInfo:dic back:^(bool issuccess) {
            
            if (issuccess) {
                _sexSwitch.on = !_sexSwitch.on;
                [Myuser sharedUser].sex = [@(!_sexSwitch.on) stringValue];
            }
        }];
    }
    if(_datePiker.date){
        
    if (tou.view != _datePiker) {
        if ((![[MyDateformater getDateString:_datePiker.date]isEqualToString:_dateBtn.currentTitle])&([_datePiker.date compare:[NSDate date]]==NSOrderedAscending)) {
            
            NSDictionary *dic = @{@"login_id":[Myuser sharedUser].login_id,@"birthday":[MyDateformater getDateString:_datePiker.date]};
            [self modifyUserInfo:dic back:^(bool isSuccess) {
                
                if (isSuccess) {
                    [UIView animateWithDuration:0.5 animations:^{

                        _backView.transform = CGAffineTransformMakeScale(0.00001, 0.000001);
                    } completion:^(BOOL finished) {
                        
                        [_backView removeFromSuperview];
                        
                        NSString *da = [NSString stringWithFormat:@"%@ 00:00:00.0",[MyDateformater getDateString:_datePiker.date]];
                        [Myuser sharedUser].birthday = da;
                        
                        [_dateBtn setTitle:[NSString stringWithFormat:@"%@",[MyDateformater getDateString:_datePiker.date]] forState:UIControlStateNormal];
                    }];
                }
            }];
            
            
        }else{
            [UIView animateWithDuration:0.5 animations:^{
                
                _backView.transform = CGAffineTransformMakeScale(0.00001, 0.000001);
            } completion:^(BOOL finished) {
                
                [_backView removeFromSuperview];
                
            }];
        }
        
    }
    }
    
    [self.view endEditing:YES];
}
- (void)modifyUserInfo:(NSDictionary *)dic back:(void(^)(bool))back
{
    [MyAFN POST:MODIFYUSERINFO parameters:dic block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        if ([[response objectForKey:@"status"]integerValue]) {
            
            back(YES);
        }else{
            back(NO);
        }
    } error:^(NSError *error) {
        back(NO);
    } fromController:self];
}

#pragma mark @"上传头像"
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == self.myActionSheet.cancelButtonIndex) {
        NSLog(@"取消");
    }
    
    switch (buttonIndex) {
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
            
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }

}

- (void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        //[self.navigationController pushViewController:picker animated:YES];
        
        [self presentViewController:picker animated:YES completion:NULL];
    } else {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }

}

-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.navigationBar.barTintColor = RGBcolor(34, 34, 34);
//    NSDictionary * dict=[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
//    picker.navigationBar.titleTextAttributes = dict;
    
    picker.delegate = self;
    //设置拍照后的图片可被编辑
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = YES;
    //[self.navigationController pushViewController:picker animated:YES];
    
    [self presentViewController:picker animated:YES completion:NULL];
}
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSDictionary *parameter = [NSDictionary dictionaryWithObject:[Myuser sharedUser].login_id forKey:@"login_id"];
    
    UIImage *ima = [info objectForKey:UIImagePickerControllerEditedImage];
    ima = [self imageWithImage:ima scaledToSize:CGSizeMake(100, 100)];
    
    [MyAFN POST:HEADPHOTO parameters:parameter withData:UIImagePNGRepresentation(ima) andDataname:@"photo" block:^(id responseObject) {
        
        NSDictionary *response = responseObject;
        if ([response objectForKey:@"status"]) {
            
            _iconIma.image = [info objectForKey:UIImagePickerControllerEditedImage];
            //    self.changeIcon([info objectForKey:UIImagePickerControllerOriginalImage]);
            NSString *url = [NSString stringWithFormat:@"%@?url=%@",GETICON,[response objectForKey:@"photo"]];
            [[NSUserDefaults standardUserDefaults]setObject:url forKey:@"usericon"];
            
            [Myuser sharedUser].icon = url;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:_iconIma.image];
        }else{
            
            [self.view performSelector:@selector(Message:) withObject:@"上传失败，请重试" afterDelay:0.5];
        }
        
    } error:^(NSError *error) {
        
    } fromController:self];
        
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)valiMobile:(NSString *)mobilePhone {
    //验证手机号
    //移动号段正则表达式
    NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
    //联通号段正则表达式
    NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
    //电信号段正则表达式
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobilePhone];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobilePhone];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobilePhone];
    
    if (isMatch1 || isMatch2 || isMatch3){
        return YES;
    }
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
